package com.chezai.client.utils;

import android.app.RootSuManager;
import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.os.StatFs;
import android.text.TextUtils;

import com.chezai.client.dao.manager.ClassRecordDaoManager;
import com.chezai.client.dao.manager.PeriodRecordDaoManager;
import com.orhanobut.logger.Logger;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.BufferedReader;
import java.io.ByteArrayOutputStream;
import java.io.Closeable;
import java.io.DataOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.List;

/**
 * 立宇泰 703B 工具类
 */
public class FileUtil {
    private final static String[][] MIME_MapTable =
            {
                    {".3gp", "video/3gpp"},
                    {".apk", "application/vnd.android.package-archive"},
                    {".asf", "video/x-ms-asf"},
                    {".avi", "video/x-msvideo"},
                    {".bin", "application/octet-stream"},
                    {".bmp", "image/bmp"},
                    {".c", "text/plain"},
                    {".class", "application/octet-stream"},
                    {".conf", "text/plain"},
                    {".cpp", "text/plain"},
                    {".doc", "application/msword"},
                    {".exe", "application/octet-stream"},
                    {".gif", "image/gif"},
                    {".gtar", "application/x-gtar"},
                    {".gz", "application/x-gzip"},
                    {".h", "text/plain"},
                    {".htm", "text/html"},
                    {".html", "text/html"},
                    {".jar", "application/java-archive"},
                    {".java", "text/plain"},
                    {".jpeg", "image/jpeg"},
                    {".jpg", "image/jpeg"},
                    {".js", "application/x-javascript"},
                    {".log", "text/plain"},
                    {".m3u", "audio/x-mpegurl"},
                    {".m4a", "audio/mp4a-latm"},
                    {".m4b", "audio/mp4a-latm"},
                    {".m4p", "audio/mp4a-latm"},
                    {".m4u", "video/vnd.mpegurl"},
                    {".m4v", "video/x-m4v"},
                    {".mov", "video/quicktime"},
                    {".mp2", "audio/x-mpeg"},
                    {".mp3", "audio/x-mpeg"},
                    {".mp4", "video/mp4"},
                    {".mpc", "application/vnd.mpohun.certificate"},
                    {".mpe", "video/mpeg"},
                    {".mpeg", "video/mpeg"},
                    {".mpg", "video/mpeg"},
                    {".mpg4", "video/mp4"},
                    {".mpga", "audio/mpeg"},
                    {".msg", "application/vnd.ms-outlook"},
                    {".ogg", "audio/ogg"},
                    {".pdf", "application/pdf"},
                    {".png", "image/png"},
                    {".pps", "application/vnd.ms-powerpoint"},
                    {".ppt", "application/vnd.ms-powerpoint"},
                    {".prop", "text/plain"},
                    {".rar", "application/x-rar-compressed"},
                    {".rc", "text/plain"},
                    {".rmvb", "audio/x-pn-realaudio"},
                    {".rtf", "application/rtf"},
                    {".sh", "text/plain"},
                    {".tar", "application/x-tar"},
                    {".tgz", "application/x-compressed"},
                    {".txt", "text/plain"},
                    {".wav", "audio/x-wav"},
                    {".wma", "audio/x-ms-wma"},
                    {".wmv", "audio/x-ms-wmv"},
                    {".wps", "application/vnd.ms-works"},
                    // {".xml", "text/xml"},
                    {".xml", "text/plain"},
                    {".z", "application/x-compress"},
                    {".zip", "application/zip"},
                    {"", "*/*"}};
    public static String TAG = "FileUtil";

    /**
     * 删除之前的文件
     * 包括：照片，下载app包，科一科四学员登出的播报语音，二维码
     */
    public static void deleteFiles() {
        ThreadManager.getInstance().getNormalPool().execute(new Runnable() {
            @Override
            public void run() {
                SDCardUtil.fileDelete(SDCardUtil.getVoiceTempDir());
                SDCardUtil.fileDelete(SDCardUtil.getTempDir());
                SDCardUtil.fileDelete(SDCardUtil.getPhotoDir());
                SDCardUtil.fileDelete(SDCardUtil.getPhotoQrDir());
                SDCardUtil.fileDelete(SDCardUtil.getLogDir());
                SDCardUtil.fileDelete(SDCardUtil.getDownloadDir());
                ClassRecordDaoManager.getInstance().deleteTimeOutData();//删除课堂记录
                PeriodRecordDaoManager.getInstance().deleteTimeOutData();//删除分钟学时
            }
        });
    }


    // *********************************************一行一行地读文件*****************************************************************************
    public static List<String> readFileByLines(String fileName) {
        File file = new File(fileName);
        try {
            if (!file.exists()) {
                file.createNewFile();
            }
        } catch (IOException e2) {
            e2.printStackTrace();
        }

        List<String> list = new ArrayList<String>();
        BufferedReader reader = null;
        try {
            reader = new BufferedReader(new FileReader(file));
            String tempString = null;

            while ((tempString = reader.readLine()) != null) {
                list.add(tempString);
            }

            reader.close();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (reader != null) {
                try {
                    reader.close();
                } catch (IOException e1) {
                }
            }
        }

        return list;
    }

    public static int writeFile_wifi(String fileName, String content, Boolean cover) {
        try {
            File file = new File(fileName);
            try {
                if (!file.exists()) {
                    file.createNewFile();
                }
            } catch (IOException e2) {
                e2.printStackTrace();
            }
            FileWriter writer = new FileWriter(fileName, cover);
            writer.write(content);
            writer.flush();
            writer.close();
        } catch (IOException e) {
            e.printStackTrace();
            return -1;
        }
        return 0;
    }

    // ********************************************************写文件********************************************************************
    public static void writeFile(String fileName, InputStream in) {
        File file = new File(fileName);

        File fileParent = file.getParentFile();
        if (!fileParent.exists()) {
            fileParent.mkdirs();
        }
        try {
            if (!file.exists()) {
                file.createNewFile();
            }
        } catch (IOException e2) {
            e2.printStackTrace();
        }

        OutputStream os = null;
        try {
            os = new FileOutputStream(file);
            byte buffer[] = new byte[4 * 1024];

            int len = 0;
            while ((len = in.read(buffer)) != -1) {
                os.write(buffer, 0, len);
            }
            os.flush();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                os.close();
            } catch (Exception e) {
                e.printStackTrace();
            }

            try {
                in.close();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }

    public static void writeFile(String fileName, String message) {
        try {
            File file = new File(fileName);
            File fileParent = file.getParentFile();
            if (!fileParent.exists()) {
                fileParent.mkdirs();
            }

            try {
                if (!file.exists()) {
                    file.createNewFile();
                }
            } catch (IOException e2) {
                e2.printStackTrace();
            }

            FileOutputStream fout = new FileOutputStream(fileName);
            byte[] bytes = message.getBytes();
            fout.write(bytes);
            fout.flush();
            fout.close();
        } catch (Exception e) {
            e.printStackTrace();
        }

    }

    public static int writeLocationToFile(String msg, String locStr) {
        String fileName = SDCardUtil.getLogDir() + "log_" + DateUtil.timestampStr(DateUtil.sf5) + ".txt";
        String content = "[" + locStr + "] " + (TextUtils.isEmpty(msg) ? "is best" : (" not best, reason " + msg)) + "\n";
        return FileUtil.writeFileAppendORCover(fileName, content, true);
    }

    public static int writeFileAppendORCover(String fileName, String content, Boolean cover) {
        try {
            File file = new File(fileName);

            File fileParent = file.getParentFile();
            if (!fileParent.exists()) {
                fileParent.mkdirs();
            }
            try {
                if (!file.exists()) {
                    file.createNewFile();
                }
            } catch (IOException e2) {
                e2.printStackTrace();
            }

            FileWriter writer = new FileWriter(fileName, cover);
            writer.write(content);
            writer.flush();
            writer.close();
        } catch (IOException e) {
            e.printStackTrace();
            return -1;
        }
        return 0;
    }

    public static void data2File(byte[] w, String fileName) throws Exception {
        FileOutputStream out = null;
        try {
            out = new FileOutputStream(fileName);
            out.write(w);
            out.close();
        } catch (Exception e) {
            if (out != null)
                out.close();
            throw e;
        }
    }

    // *****************************************************备份文件*******************************************************************************
    public static void backupFile(String fileName, String fileName_bak) {
        File file = new File(fileName);
        File file_bak = new File(fileName_bak);
        try {
            if (!file.exists()) {
                file.createNewFile();
            }
            if (!file_bak.exists()) {
                file_bak.createNewFile();
            }
        } catch (IOException e2) {
            e2.printStackTrace();
        }

        if (file.length() >= file_bak.length()) {
            if (!copyFile(fileName, fileName_bak)) {
            }
        } else {
        }
    }

    /**
     * 复制文件
     *
     * @param from 来源文件路径
     * @param to   复制到 路径
     * @return
     */
    public static boolean copyFile(String from, String to) {
        File fromFile, toFile;
        fromFile = new File(from);
        toFile = new File(to);
        FileInputStream fis = null;
        FileOutputStream fos = null;
        try {
            fis = new FileInputStream(fromFile);
            fos = new FileOutputStream(toFile);
            int bytesRead;
            byte[] buf = new byte[256 * 1024];// 256K buffer
            while ((bytesRead = fis.read(buf)) != -1) {
                fos.write(buf, 0, bytesRead);
            }
        } catch (IOException e) {
            return false;
        } finally {
            try {
                if (fis != null) {
                    fis.close();
                }
                if (fos != null) {
                    fos.flush();
                    fos.close();
                }
            } catch (IOException e) {
                Logger.t(TAG).i("copy file stream close failed");
            }
        }

        return true;

    }

    // *****************************************************************删除文件*********************************************************
    public static boolean delDirectory(String path) {
        boolean flag = false;
        File file = new File(path);
        if (!file.exists()) {
            return flag;
        }
        if (!file.isDirectory()) {
            return flag;
        }
        String[] tempList = file.list();
        File temp = null;
        for (int i = 0; i < tempList.length; i++) {
            if (path.endsWith(File.separator)) {
                temp = new File(path + tempList[i]);
            } else {
                temp = new File(path + File.separator + tempList[i]);
            }
            if (temp.isFile()) {
                temp.delete();
            }
            if (temp.isDirectory()) {
                delDirectory(path + "/" + tempList[i]);
                delFolder(path + "/" + tempList[i]);
                flag = true;
            }
        }
        return flag;
    }

    private static void delFolder(String folderPath) {
        try {
            delDirectory(folderPath);
            String filePath = folderPath;
            filePath = filePath.toString();
            File myFilePath = new File(filePath);
            myFilePath.delete();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    // *************************************************************判断文件是否存在******************************************************************
    public static boolean isFileExists(String filename) {
        if (filename == null)
            return false;

        File file = new File(filename);
        return file.exists();
    }

    // *************************************************************获取存储空间大小******************************************************************
    public static long getMemorySize(String path) {
        if (path == null) {
            return 0;
        }
        StatFs statfs = new StatFs(path);
        long blockSize = statfs.getBlockSize();
        long availableBlocks = statfs.getAvailableBlocks();
        return blockSize * availableBlocks / (1024 * 1024);
    }

    // ************************************************************修改文件属性**********************************************************************
    public static void execCommand(String command) {
        Process process = null;
        DataOutputStream os = null;
        try {
            // ProcessBuilder builder = new ProcessBuilder("su");
            // builder.redirectErrorStream(false);
            // process = builder.start();
            process = Runtime.getRuntime().exec("su hzliyutai");
            InputStream inputstream = process.getInputStream();
            InputStreamReader inputstreamreader = new InputStreamReader(
                    inputstream);
            BufferedReader bufferedreader = new BufferedReader(
                    inputstreamreader);
            os = new DataOutputStream(process.getOutputStream());
            os.writeBytes(command + "\n");
            os.writeBytes("exit\n");
            os.flush();

            String line = "";
            StringBuilder sb = new StringBuilder(line);
            while ((line = bufferedreader.readLine()) != null) {

                sb.append(line);

                sb.append('\n');

            }
            process.waitFor();
        } catch (Exception e) {
            Logger.t(TAG).d("Unexpected error - Here is what I know: " + e.getMessage());
            Logger.t(TAG).i("why1" + e.getMessage());
        }

    }

    //*****************************获取root权限安装apk**********
    public static void execCommand(Context context, String command, String filePath) {
        RootSuManager mRootSuManager = (RootSuManager) context.getSystemService(Context.RootSu_SERVICE);
        if (mRootSuManager != null) {
            String result = mRootSuManager.RootCommand(command);
            Logger.t(TAG).i("execCommand: " + result);
        } else {
            Intent intentPath = new Intent(Intent.ACTION_VIEW);
            intentPath.setDataAndType(Uri.parse(filePath), "application/vnd.android.package-archive");
            intentPath.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
            context.startActivity(intentPath);
        }
    }

    // *************************************************************获取文件的MIMEType属性*************************************************************
    public static String getMIMEType(File file) {

        String type = "*/*";
        String fName = file.getName();
        int dotIndex = fName.lastIndexOf(".");
        if (dotIndex < 0) {
            return type;
        }
        String end = fName.substring(dotIndex, fName.length()).toLowerCase();
        if (end == "")
            return type;

        for (int i = 0; i < MIME_MapTable.length; i++) {
            if (end.equals(MIME_MapTable[i][0]))
                type = MIME_MapTable[i][1];
        }
        return type;
    }

    public static byte[] fileToByte(File file) {
        try {
            byte[] buffer = null;
            FileInputStream fis = new FileInputStream(file);
            ByteArrayOutputStream bos = new ByteArrayOutputStream(1000);
            byte[] b = new byte[1000];
            int n;
            while ((n = fis.read(b)) != -1) {
                bos.write(b, 0, n);
            }
            fis.close();
            bos.close();
            buffer = bos.toByteArray();
            return buffer;
        } catch (FileNotFoundException e) {
            e.printStackTrace();
            return null;
        } catch (IOException e) {
            e.printStackTrace();
            return null;
        }
    }


    public static void copyDatabase(Context ctx) {
        File db = ctx.getDatabasePath("terminal-db");
        File copyDb = new File(SDCardUtil.getDownLoadRootDirPath() + "terminal_copy-db.db");
        if (copyDb.exists()){
            copyDb.delete();
        }
        BufferedInputStream bis = null;
        BufferedOutputStream bos = null;
        FileInputStream fis = null;
        FileOutputStream fos = null;
        try {
            fis = new FileInputStream(db);
            fos = new FileOutputStream(copyDb);
            bis = new BufferedInputStream(fis);
            bos = new BufferedOutputStream(fos);
            byte[] bytes = new byte[10 * 1024];
            int length = 0;
            while (length != -1) {
                length = bis.read(bytes);
                bos.write(bytes);
            }
            bos.flush();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            closeIO(bis);
            closeIO(bos);
            closeIO(fis);
            closeIO(fos);
        }
    }

    public static void closeIO(Closeable closeable) {
        try {
            if (closeable != null) {
                closeable.close();
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }


}
